
package ch.usi.inf.pf2;

import java.io.*;


/**
 * This class contains some methods used to read data contained into a file and creates a new SpreadSheet
 * @author Lorenzo Baracchi, changes by Milan Jovic
 */
public class ReadSpreadSheetFile
{
	private Sheet sheetReaded;
	private String fileToRead;
	
	public ReadSpreadSheetFile (String fileToRead)
	{
		sheetReaded=new Sheet(); 
		sheetReaded.initializeSheet();
		this.fileToRead=fileToRead + ".CSV";
	}
	
	/**
	 * Divide a read line in the values that it contains on the comma. (actually ",")
	 * @param line the line to divide
	 * @return the values contained in the line
	 */
	public static String[] cutLineOnComma (String line)
	{
		String[] cutted=line.split(",");
/*		for(int i=0; i<cutted.length; i++)
		{
			if(cutted[i].charAt(0)=='"')
				cutted[i]=cutted[i].substring(1); //delete the " at the beginning of the value
			if(cutted[i].endsWith("\",")) //delete the ", at the end of the last value
				cutted[i]=cutted[i].substring(0, cutted[i].length()-2);
			if(cutted[i].endsWith("\",\n")) //delete the ", at the end of the last value of a row
				cutted[i]=cutted[i].substring(0, cutted[i].length()-3);
		}				
*/		
		return cutted;
	}
	
	/**
	 * Check if the file exists
	 * @return true if exist false otherwise
	 */
	public boolean tryToOpenFile () 
	{
		File newFile = new File(fileToRead);
		return newFile.exists();
	}
	
	/**
	 * Read the given file and create a new Sheet
	 * @return the sheet read
	 * @throws IOException 
	 * @throws IOException if the file doesn't exists
	 */
	public Sheet readSheet () throws IOException 
	{
		if(!tryToOpenFile())
		{
			//file not found
			throw new IOException("File not found");
		}
		else
		{
			RandomAccessFile rnd=null;
			try {
				System.out.println("*** " + fileToRead);
				rnd = new RandomAccessFile(fileToRead, "r");
			} catch (FileNotFoundException e1) {
				System.out.println("File not found exception raised");
			}
			String read;
			int lineNumber=1;
			try{
				while((read=rnd.readLine()) != null)
				{	
					String[] splitted = this.cutLineOnComma(read); 
					for(int i=0; i<splitted.length; i++)
						sheetReaded.insertDataAtCellForInit(splitted[i], i+1, lineNumber); 
					lineNumber++;
				}
			}
			catch (EOFException e)
			{
				System.out.println("error reading the file");
				// exception raised when readUtf reaches the end of file
				return sheetReaded;
			}
		}
		return sheetReaded;
	}
}